import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/ecycommon/EcyAPI.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/blind_box_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../constant/EcyEventConsnt.dart';
import '../../../ecycommon/EcyEventBus.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../goods/model/CommodityTop.dart';

class BlindBoxPage extends StatefulWidget {
  late _BlindBoxPageState state;

  BlindBoxPage({required super.key});

  @override
  State<StatefulWidget> createState() {
    state = _BlindBoxPageState();
    return state;
  }

  reloadData(String search) {
    state._refreshData(search);
  }
}

class _BlindBoxPageState extends State<BlindBoxPage> {
  _BlindBoxPageState();

  final RefreshController _refreshControllerFirst = RefreshController(initialRefresh: false);
  final RefreshController _refreshControllerSec = RefreshController(initialRefresh: false);

  int _currentPage = 1;
  bool _hasMore = false;

  final List<int> indexList = List.filled(19, 0);
  final List<BlindBoxPageCommodity> _commodityTopList = [];

  @override
  void initState() {
    super.initState();
    initNotis();
    _refreshData("");
  }

  initNotis() {
    EcyEventBus().on(EcyEventConst.kHttpConnected, (arg) {
      _refreshData("");
    });
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    await _refreshData("");
    // 重置上拉加载状态
    _refreshControllerFirst.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshControllerSec.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      Map<String, dynamic> body = {
        "current": _currentPage,
        "size": 100,
        "search": search,
      };
      var response = await EcyRequestbasemanager().post(EcyAPI.blindBoxSeries.url, body);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<BlindBoxPageCommodity> commonPage =
              EcyApiCommonPage.fromJson(response["data"], (json) => BlindBoxPageCommodity.fromJson(json));
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          var blindBoxPageCommodityList = commonPage.records ?? [];
          if (_currentPage == 1) {
            _commodityTopList.clear();
          }
          setState(() {
            _commodityTopList.addAll(blindBoxPageCommodityList);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取盲抽失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_commodityTopList.isEmpty) {
      return Container(
          color: const Color(0xFFF5F5F5),
          margin: EdgeInsets.only(top: 5.h),
          width: MediaQuery.of(context).size.width,
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: false,
            physics: const AlwaysScrollableScrollPhysics(),
            header: const ClassicHeader(
              refreshStyle: RefreshStyle.Follow,
              idleText: '下拉刷新',
              refreshingText: '加载中...',
              completeText: '刷新完成',
              failedText: '刷新失败',
              textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
              releaseText: '松开刷新',
              iconPos: IconPosition.top,
              spacing: 8,
            ),
            onRefresh: () => _onRefresh1(),
            controller: _refreshControllerFirst,
            child: ListView.builder(
              shrinkWrap: true,
              physics: const AlwaysScrollableScrollPhysics(),
              padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
              itemCount: 1,
              itemBuilder: (context, index) {
                return Column(
                  children: [
                  Padding(padding: EdgeInsets.only(top: 70.h)),
                  Image.asset('assets/images/empty/ic_empty_search.png', width: 150, height: 150),
                    const Text('盲盒待更新', style: TextStyle(fontSize: 18, color: Colors.grey)),
                  ],
                );
              },
            ),
          )
        );
    }

    return Flexible(
        child: Container(
            color: const Color(0xFFF5F5F5),
            child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              physics: const AlwaysScrollableScrollPhysics(),
              header: const ClassicHeader(
                refreshStyle: RefreshStyle.Follow,
                idleText: '下拉刷新',
                refreshingText: '加载中...',
                completeText: '刷新完成',
                failedText: '刷新失败',
                textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
                releaseText: '松开刷新',
                iconPos: IconPosition.top,
                spacing: 8,
              ),
              footer: CustomFooter(
                builder: (BuildContext context, LoadStatus? mode) {
                  Widget body;
                  if (mode == LoadStatus.idle) {
                    body = const Text("上拉加载更多", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.loading) {
                    body = const Text("加载中...", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.failed) {
                    body = const Text("加载失败，点击重试", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.canLoading) {
                    body = const Text("松手加载更多", style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else {
                    body = const Text("没有更多盲盒了", style: TextStyle(color: Color(0xFF8C8C8C)));
                  }
                  return SizedBox(
                    height: 35.w,
                    child: Center(child: body),
                  );
                },
              ),
              onRefresh: () => _onRefresh2(),
              onLoading: () => _onLoading2(),
              controller: _refreshControllerSec,
              child: ListView.builder(
                shrinkWrap: true,
                physics: const ClampingScrollPhysics(),
                itemCount: _commodityTopList.length,
                itemBuilder: (BuildContext context, int index) {
                  var blindBoxPageCommodity = _commodityTopList[index];
                  return GestureDetector(
                      child: _buildCard(blindBoxPageCommodity),
                      onTap: () {
                        EcyRouter.push(context, EcyRouter.blindBoxMorePage, {"ipCode": blindBoxPageCommodity.ipCode,"ipName": blindBoxPageCommodity.ipName});
                      });
                },
              ),
            )));
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png', width: 80.w, height: 80.h, fit: BoxFit.contain);

  Card _buildCard(BlindBoxPageCommodity blindBoxPageCommodity) {
    return Card(
      color: Colors.white,
      margin: const EdgeInsets.all(8),
      child: SizedBox(
        height: 203.h,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 14.w),
              child: SizedBox(
                height: 54.h,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '${blindBoxPageCommodity.ipName}',
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w900,
                        fontSize: 16.sp,
                        color: const Color(0xFF262626),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                       EcyRouter.push(context, EcyRouter.blindBoxMorePage, {"ipCode": blindBoxPageCommodity.ipCode,"ipName": blindBoxPageCommodity.ipName});
                      },
                      child: Text(
                        'more>>',
                        style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w900,
                          fontSize: 14.sp,
                          color: const Color(0xFF262626),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
                child: GridView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3, //每行三列
                    childAspectRatio: 0.8,
                  ),
                  itemCount: blindBoxPageCommodity.blindBoxDetailVoList?.length ?? 0,
                  itemBuilder: (context, index) {
                    final item = blindBoxPageCommodity.blindBoxDetailVoList?[index];
                    if (item == null) return Container();
                    
                    return GestureDetector(
                      onTap: () {
                        // EcyRouter.push(context, EcyRouter.blindBoxEnter, {
                        //   'commodityId': item.commodityId,
                        // });
                      },
                      child: Column(
                        children: [
                          SizedBox(
                            height: 109.h,
                            width: 109.w,
                            child: DecoratedBox(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                border: Border.all(
                                  color: const Color(0x10EA4B9B),
                                  width: 2,
                                ),
                              ),
                              child: Padding(
                                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h),
                                child: CachedNetworkImage(
                                  width: 80.w,
                                  height: 80.h,
                                  imageUrl: item.mainImageUrl ?? '',
                                  imageBuilder: (context, imageProvider) => Container(
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                      image: DecorationImage(
                                        image: imageProvider,
                                        fit: BoxFit.cover
                                      )
                                    ),
                                  ),
                                  placeholder: (context, url) => avatar,
                                  errorWidget: (context, url, error) => avatar,
                                ),
                              ),
                            ),
                          ),
                          Container(
                            height: 40.h,
                            padding: EdgeInsets.only(top: 5.h),
                            child: Text(
                              item.commodityName ?? '未知商品',
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w700,
                                fontSize: 12.sp,
                                color: const Color(0xFF262626),
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                )
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _refreshControllerFirst.dispose();
    _refreshControllerSec.dispose();
    super.dispose();
  }
}
